<template>
  <el-dialog
    title="新增学生"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="700px"
  >
    <el-form
      :model="studentForm"
      :rules="studentFormRules"
      ref="studentForm"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="real_name">
            <el-input
              v-model="studentForm.real_name"
              placeholder="请输入姓名"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账号" prop="username">
            <el-input
              v-model="studentForm.username"
              placeholder="请输入账号"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select
              v-model="studentForm.sex"
              placeholder="请选择性别"
              clearable
            >
              <el-option label="男" :value="0"></el-option>
              <el-option label="女" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="生日" prop="birth_date">
            <el-date-picker
              v-model="studentForm.birth_date"
              type="date"
              placeholder="请选择生日"
              clearable
              class="date-picker"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <el-input
              v-model="studentForm.contacts"
              placeholder="请输入联系人"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contacts_mobile">
            <el-input
              v-model="studentForm.contacts_mobile"
              placeholder="请输入联系方式"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="线下学校">
            <el-select
              v-model="studentForm.school_id"
              filterable
              remote
              reserve-keyword
              placeholder="请选择线下学校"
              :remote-method="getOfflineSchool"
              :loading="loading"
              @change="handleSelect()"
            >
              <el-option
                v-for="item in offlineSchool"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="线下班级" prop="class_id">
            <el-cascader
              v-model="studentForm.class_id"
              :options="gradeList"
              @active-item-change="changeHandle"
              placeholder="请选择线下班级"
              :disabled="!studentForm.school_id"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
                <el-form-item label="用户渠道" prop="user_channel" >
                    <nice-select v-model="studentForm.user_channel" placeholder="请选择用户渠道" clearable :options="userChannelList"></nice-select>
                </el-form-item>
              </el-col> -->
        <el-col :span="24">
          <el-form-item label="邮寄地址" prop="address">
            <el-input
              v-model="studentForm.address"
              placeholder="请输入邮寄地址"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="small">取消</el-button>
      <el-button
        type="primary"
        @click="dataFormSubmit"
        size="small"
        v-preventReClick
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { addStudent, queryPageList, getGrade } from '@/api/user'
import { cascadeQuery } from '@/api/api.js'
import { myEnumsMixins } from '@/utils/mixins'
export default {
  data () {
    const validateMobile = (rule, value, callback) => {
      if (!this.$valid.isMobile(value)) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      coverGradeList: [],
      userChannelList: [],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      studentForm: {
        real_name: '',
        username: '',
        sex: '',
        birth_date: '',
        contacts: '',
        contacts_mobile: '',
        address: '',
        school_id: '',
        // user_channel: '',
        class_id: []
      },
      offlineSchool: [],
      loading: false,
      gradeList: [],
      studentFormRules: {
        real_name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        contacts_mobile: [
          { required: true, message: '联系方式不能为空', trigger: 'blur' },
          { validator: validateMobile, trigger: 'blur' }
        ],
        // user_channel: [
        //       { required: true, message: '用户渠道不能为空', trigger: 'change' }
        // ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/(^[1-9]\d*$)/.test(value)) {
                callback('请输入1到20位数字！') //eslint-disable-line
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mixins: [myEnumsMixins],
  props: {
    source: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  methods: {
    init () {
      // this.userChannelList = this.selectEnums.nice_user_base.user_channel.map(ele => {
      //   return {
      //     label: ele.label,
      //     value: ele.real_value
      //   }
      // })
      this.visible = true
      this.$nextTick(() => {
        this.studentForm.school_id = ''
        this.gradeList = []
        this.$refs['studentForm'].resetFields()
        this.$refs['studentForm'].resetFields()
      })
    },
    handleSelect (val) {
      this.gradeList = []
      this.studentForm.class_id = []
      let coveragegrade =
        this.offlineSchool &&
        this.offlineSchool.filter(ele => {
          return ele.value === this.studentForm.school_id
        })[0]
      this.coverGradeList = []
      this.selectEnums.nice_school.coverage_grade.forEach(ele => {
        coveragegrade.nursery_grade &&
          ele.label === '幼儿园' &&
          this.coverGradeList.push(ele.value)
        coveragegrade.junior_grade &&
          ele.label === '小学' &&
          this.coverGradeList.push(ele.value)
        coveragegrade.middle_grade &&
          ele.label === '初中' &&
          this.coverGradeList.push(ele.value)
        coveragegrade.high_grade &&
          ele.label === '高中' &&
          this.coverGradeList.push(ele.value)
      })
      this.getGrade()
    },
    async getGrade () {
      this.gradeList = []
      let res = await getGrade({ grade: this.coverGradeList })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        res[1].data.forEach(ele => {
          this.gradeList.push({
            label: ele.display_value,
            value: ele.t_id,
            children: []
          })
        })
      }
    },
    async changeHandle (val) {
      let res = await cascadeQuery({
        table_name: 'nice_school_classes',
        condition: {
          school_id: this.studentForm.school_id,
          init_grade: val[0]
        }
      })
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.gradeList.forEach(ele => {
          if (ele.value === val[0]) {
            ele.children = res[1].data.map(item => {
              return { label: item.class_name, value: item.id }
            })
          }
        })
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async getOfflineSchool (query) {
      if (query !== '') {
        this.loading = true
        let form = {
          table_name: 'nice_school',
          'nice_school.school_name': query
        }
        let res = await queryPageList(form)
        if (res[0]) {
          return
        }
        let data = res[1]
        this.loading = false
        if (data && data.code === 0) {
          if (data.data.pageList.list && data.data.pageList.list.length) {
            this.offlineSchool = data.data.pageList.list.map(item => {
              return {
                label: item.school_name,
                value: item.id,
                nursery_grade: item.nursery_grade,
                junior_grade: item.junior_grade,
                middle_grade: item.middle_grade,
                high_grade: item.high_grade
              }
            })
          } else {
            this.offlineSchool = []
          }
        }
      }
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['studentForm'].validate(valid => {
        if (valid) {
          let form = {
            'sys_user.username': this.studentForm.username,
            'nice_user_base.real_name': this.studentForm.real_name,
            'nice_user_base.sex': this.studentForm.sex,
            'nice_user_base.birth_date': this.studentForm.birth_date,
            'nice_user_base.address': this.studentForm.address,
            'nice_student_contacts.contacts': this.studentForm.contacts,
            'nice_user_base.mobile': this.studentForm.contacts_mobile,
            'nice_student_contacts.contacts_mobile': this.studentForm
              .contacts_mobile,
            'nice_student.school_id': this.studentForm.school_id,
            'nice_student.grade': this.studentForm.class_id[0],
            'nice_student.school_class_id': this.studentForm.class_id[1],
            'nice_student.source': this.source[1].value,
            'nice_student_contacts.is_default': '1'
            // 'nice_user_base.user_channel': this.studentForm.user_channel
          }
          this.submit(form)
        }
      })
    },
    async submit (e) {
      let res = await addStudent(e)
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message: '新增成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    }
  }
}
</script>
